package com.yinile.zc03.spec;

import java.util.ArrayList;
import com.yinile.zc03.sys.utils.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import com.yinile.zc03.domain.Author;

public class AuthorSpecImpl implements Specification<Author> {
	
	private String name;
	private String address;
	

	public AuthorSpecImpl(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}


	@Override
	public Predicate toPredicate(Root<Author> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		ArrayList<Predicate> predicateList = new ArrayList<Predicate>(2);
		if (StringUtils.isNotEmpty(this.name)) {
			StringBuffer sb = new StringBuffer("%").append(this.name).append("%");
			predicateList.add(cb.like(root.get("name"), sb.toString()));
		}
		if (StringUtils.isNotEmpty(this.address)) {
			StringBuffer sb2 = new StringBuffer("%").append(this.address).append("%");
			predicateList.add(cb.like(root.get("address"), sb2.toString()));
		}
		// 根据有没有查询条件来选择返回结果
		if (predicateList.isEmpty()) {
			return cb.conjunction(); // sql: where 1=1
		} else {
			Predicate[] array = new Predicate[predicateList.size()];
			predicateList.toArray(array);
			return cb.and(array);
		}
	}

}
